import { Article, Channel } from '@/types/data'
import { UserChannelType } from '@/types/store'
type ChannelUser = {
  userChannel: Channel[]
  allChannel: Channel[]
  activeId: number
  articlesChannel: {
    [key: number]: { articles: Article[]; pre_timestamp: string }
  }
}
// 用户信息的reducer
function channelReducer (
  state: ChannelUser = {
    userChannel: [],
    allChannel: [],
    activeId: 0,
    articlesChannel: {}
  },
  action: UserChannelType
) {
  switch (action.type) {
    // 存储 用户信息
    case 'user/channel':
      return { ...state, userChannel: action.payload }
    case 'all/Channel':
      return { ...state, allChannel: action.payload }
    case 'activeId/set':
      return { ...state, activeId: action.payload }
    case 'article/channel': {
      const { channelId, articles, pre_timestamp } = action.payload
      const oldArt = state.articlesChannel[channelId]?.articles || []
      return {
        ...state,
        articlesChannel: {
          ...state.articlesChannel,
          [channelId]: {
            articles: [...oldArt, ...articles],
            pre_timestamp
          }
        }
      }
    }
    case 'refrech/article': {
      const { channelId, articles, pre_timestamp } = action.payload
      return {
        ...state,
        articlesChannel: {
          ...state.articlesChannel,
          [channelId]: {
            articles: [...articles],
            pre_timestamp
          }
        }
      }
    }
    default:
      return state
  }
}

export default channelReducer
